package com.coda.service.impl;

import com.coda.adminVo.attr.AttrKeyVo;
import com.coda.entity.AttrKey;
import com.coda.entity.AttrValue;
import com.coda.mapper.AttrMapper;
import com.coda.service.AttrService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

@Service
public class AttrServiceImpl implements AttrService {
    @Autowired
    private AttrMapper attrMapper;

    /**
     * 新增或更新属性值
     *
     * @param attrValue
     */
    @Override
    public void saveOrUpdateValue(AttrValue attrValue) {
        //id为空：insert，id不为空：update
        if (attrValue.getId() == null) {
            attrMapper.insertValue(attrValue);
        } else {
            attrMapper.updateValue(attrValue);
        }
    }

    /**
     * 更新或新增属性名
     *
     * @param attrKey
     */
    @Override
    public void saveOrUpdateKey(AttrKey attrKey) {
        if (attrKey.getId() == null) {
            attrMapper.insertKey(attrKey);
        } else {
            attrMapper.updateKey(attrKey);

        }
    }

    /**
     * 查看全部属性名称和属性值列表
     *
     * @return
     */
    @Override
    public List<AttrKeyVo> list() {
        List<AttrKeyVo> attrKeyVos = new ArrayList<>();

        //获取attrKey所有信息
        List<AttrKey> attrKeys = attrMapper.getKey();
        //创建集合对象存放arrt

        //遍历attrKeys
        for (AttrKey attrKey : attrKeys) {
            //创建对象，存放单次查找的数据
            AttrKeyVo attrKeyVo = new AttrKeyVo();

            attrKeyVo.setId(attrKey.getId());
            attrKeyVo.setName(attrKey.getName());

            //通过key_id获取对应的value
            List<AttrValue> attrValues = attrMapper.getValue(attrKey.getId());
            attrKeyVo.setAttrValueList(attrValues);

            //最后存放进attrKeyVo
            attrKeyVos.add(attrKeyVo);
        }
        return attrKeyVos;
    }

    /**
     * 根据id删除属性值
     *
     * @param id
     */
    @Override
    public void deleteValueById(Long id) {
        attrMapper.deleteValueById(id);
    }

    /**
     * 根据id删除名称
     * @param
     */
    @Transactional
    @Override
    public void deleteKeyById(Long attrKeyId) {
        //删除属性名
        attrMapper.deleteKeyById(attrKeyId);

        //删除属性名对应的属性值
        attrMapper.deleteValueByKeyId(attrKeyId);
    }
}
